<template>
  <div>
    <el-card shadow="always">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名：">
          <el-input v-model="keyword" placeholder="请你输入搜索用户名" clearable />
        </el-form-item>
        <el-form-item label="">
          <el-button :disabled="keyword ? false : true" type="primary" size="default" @click="search">搜索</el-button>
          <el-button size="default" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card v-loading="loading" shadow="always" class="table-box">
      <el-button v-has="'btn.User.add'" type="primary" size="default" @click="addUser">添加用户</el-button>
      <el-button v-has="'btn.User.remove'" type="danger" size="default" :desabled="selectIdArr.length ? false : true" @click="deleteSelectUser">批量删除</el-button>
      <el-table :data="userArr" border stripe style="margin-top: 20px" @select="selectUser">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" align="center" />
        <el-table-column label="id" align="center" prop="id" />
        >
        <el-table-column label="用户名字" align="center" prop="name" />
        <el-table-column label="用户角色" align="center" prop="roleName" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />
        <el-table-column label="操作" width="300px" align="center" fixed="right">
          <template #default="{ row }">
            <el-button v-has="'btn.User.assgin'" type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
            <el-button v-has="'btn.User.update'" type="primary" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
            <el-popconfirm :title="`确定要删除${row.name}吗？`" @confirm="deleteUser(row.id)">
              <template #reference>
                <el-button v-has="'btn.User.remove'" type="danger" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]" layout="prev, pager, next, jumper,->, sizes,total" :total="total" background style="margin-top: 10px" @change="getHasUser" />
    </el-card>

    <!-- 抽屉效果 -->
    <el-drawer v-model="showDrawer" :title="userParams.id ? '修改用户' : '添加用户'" direction="rtl" size="350px" :destroy-on-close="true" :show-close="true" :wrapperClosable="true">
      <template #default>
        <el-form ref="formRef" :model="userParams" :rules="rules" label-width="80px" :inline="false">
          <el-form-item label="用户姓名" prop="username">
            <el-input v-model="userParams.username" placeholder="请您输入用户姓名" />
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input v-model="userParams.name" placeholder="请您输入用户昵称" />
          </el-form-item>
          <el-form-item v-if="!userParams.id" label="用户密码" prop="password">
            <el-input v-model="userParams.password" placeholder="请您输入用户密码" />
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <el-button size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="save">确定</el-button>
      </template>
    </el-drawer>

    <el-drawer v-model="showDrawer1" title="分配角色(职位)" direction="rtl" size="350px" :destroy-on-close="true" :show-close="true" :wrapperClosable="true">
      <template #default>
        <el-form :inline="false">
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.username" :disabled="true" />
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-checkbox v-model="checkedAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
            <el-checkbox-group v-model="userRole" @change="handleCheckChange">
              <el-checkbox v-for="(item, _index) in allRole" :key="item" :label="item" :value="item">{{ item.roleName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button size="default" @click="showDrawer1 = false">取消</el-button>
        <el-button type="primary" size="default" @click="confirmClick">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import useLayOutSettingStore from '@/store/modules/setting';

import { reqUserInfo, reqAddOrUpdateUser, reqAllRole, reqSetUserRole, reqDeleteUser, reqDeleteAllUser } from '@/api/acl/user';

import type { UserResponseData, Records, User, AllRoleResponseData, AllRole } from '@/api/acl/user/type';
import { ElMessage } from 'element-plus';

onMounted(() => {
  getHasUser();
});

// 页码，单页数量，总数
let pageNo = ref<number>(1);
let pageSize = ref<number>(5);
let lastPageSize = ref<number>(5);
let total = ref<number>(100);

//表格展示数据
let userArr = ref<Records>([]);

//节流阀兼loading控制器
let loading = ref<boolean>(false);

//控制抽屉的显示与隐藏
let showDrawer = ref<boolean>(false);

//控制分配角色抽屉的显示与隐藏
let showDrawer1 = ref<boolean>(false);

//手机用户信息
let userParams = ref<User>({
  username: '',
  name: '',
  password: '',
});

//用户名字校验
const validatorUsername = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback();
  } else {
    callback(new Error('用户名长度不能小于5位'));
  }
};

//用户昵称校验
const validatorName = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback();
  } else {
    callback(new Error('用户昵称长度不能小于5位'));
  }
};

//用户密码校验
const validatorPassword = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 6) {
    callback();
  } else {
    callback(new Error('用户密码长度不能小于6位'));
  }
};

//表单校验规则
const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
};

//请求用户表单数据
const getHasUser = async (num: number = 1) => {
  if (loading.value) return;
  loading.value = true;
  if (lastPageSize.value !== pageSize.value) {
    pageNo.value = 1;
    lastPageSize.value = pageSize.value;
  } else {
    pageNo.value = num;
  }

  let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value, keyword.value);
  if (result.code === 200) {
    total.value = result.data.total;
    userArr.value = result.data.records;
  }

  loading.value = false;
};

//添加用户显示抽屉
const addUser = () => {
  Object.assign(userParams.value, {
    id: '',
    username: '',
    name: '',
    password: '',
  });
  showDrawer.value = true;
  nextTick(() => {
    formRef.value.clearValidate('username');
    formRef.value.clearValidate('name');
    formRef.value.clearValidate('password');
  });
};

//修改用户显示抽屉
const updateUser = (row: User) => {
  Object.assign(userParams.value, {
    username: '',
    name: '',
    password: '',
  });
  Object.assign(userParams.value, row);
  showDrawer.value = true;
  nextTick(() => {
    formRef.value.clearValidate('username');
    formRef.value.clearValidate('name');
  });
};

//保存用户信息的节流阀
let loading_save = ref<boolean>(false);

// 获取form组件实例
const formRef = ref();
//保存用户信息
const save = async () => {
  if (loading_save.value) return;
  loading_save.value = true;
  let value = await formRef.value.validate();

  if (!value) {
    loading_save.value = false;
    return;
  }
  let result: any = await reqAddOrUpdateUser(userParams.value);
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: userParams.value.id ? '修改成功' : '添加成功',
    });

    // getHasUser(userParams.value.id ? pageNo.value : 1);
    window.location.reload();
  } else {
    ElMessage({
      type: 'error',
      message: userParams.value.id ? '修改失败' : '添加失败',
    });
  }
  showDrawer.value = false;
  loading_save.value = false;
};

//取消
const cancel = () => {
  showDrawer.value = false;
};

//分配权限是否全选
let checkedAll = ref<boolean>(false);
//存储所有角色
let allRole = ref<AllRole>([]);
//角色
let userRole = ref<AllRole>([]);

//决定全选复选框是否半选
let isIndeterminate = ref<boolean>(true);

//分配权限全选复选框回调事件
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : [];
  isIndeterminate.value = false;
};

//分配权限多选选项组的回调事件
const handleCheckChange = (value: string[]) => {
  checkedAll.value = value.length === allRole.value.length;
  isIndeterminate.value = userRole.value.length > 0 && userRole.value.length < allRole.value.length;
};

//分配角色按钮的回调
const setRole = async (row: User) => {
  Object.assign(userParams.value, row);
  showDrawer1.value = true;

  let result: AllRoleResponseData = await reqAllRole(userParams.value.id as number);
  if (result.code === 200) {
    allRole.value = result.data.allRolesList;
    userRole.value = result.data.assignRoles;
    showDrawer1.value = true;
  }
};

//分配角色确认按钮的节流阀
let loading_confirm = ref<boolean>(false);

//分配角色确认按钮
const confirmClick = async () => {
  if (loading_confirm.value) return;
  loading_confirm.value = true;
  let result = await reqSetUserRole({
    userId: userParams.value.id as number,
    roleIdList: userRole.value.map((item) => item.id) as number[],
  });
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '分配职务成功',
    });
    showDrawer1.value = false;
    getHasUser();
  } else {
    ElMessage({
      type: 'error',
      message: '分配职务失败',
    });
  }
  loading_confirm.value = false;
};

//删除用户的节流阀
let loading_delete = ref<boolean>(false);

//删除用户
const deleteUser = async (row: User) => {
  if (loading_delete.value) return;
  loading_delete.value = true;
  let result = await reqDeleteUser(row.id as number);
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
    showDrawer1.value = false;
    if (userArr.value.length === 1 && pageNo.value !== 1) {
      pageNo.value -= 1;
    }
    getHasUser();
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    });
  }
  loading_delete.value = false;
};

let selectIdArr = ref<number[]>([]);

//表单用户选择
const selectUser = (value: User[]) => {
  selectIdArr.value = value.map((item) => item.id) as number[];
};

//批量删除用户的节流阀
let loading_deleteSelect = ref<boolean>(false);

//批量删除用户信息
const deleteSelectUser = async () => {
  if (loading_deleteSelect.value) return;
  loading_deleteSelect.value = true;
  let result = await reqDeleteAllUser(selectIdArr.value);
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '批量删除成功',
    });
    if (userArr.value.length === selectIdArr.value.length && pageNo.value !== 1) {
      pageNo.value -= 1;
    }
    getHasUser();
  } else {
    ElMessage({
      type: 'error',
      message: '批量删除失败',
    });
  }
  loading_deleteSelect.value = false;
};

//收集用户输入的搜索关键字
let keyword = ref<string>('');

//搜索事件
const search = () => {
  getHasUser();
  keyword.value = '';
};

//pinia->store中refresh控制重置
const layOutSettingStore = useLayOutSettingStore();

//重置事件
const reset = () => {
  layOutSettingStore.refresh = !layOutSettingStore.refresh;
};
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
}

.table-box {
  margin-top: 10px;
}
</style>
